<template>
	<view class="container">
		<!-- 顶部操作栏 -->
		<view class="cart-header">
			<text class="cart-title">购物车</text>
			<text class="edit-text" @click="toggleEditMode">{{ isEditMode ? '完成' : '编辑' }}</text>
		</view>

		<!-- 购物车为空提示 -->
		<view class="empty-cart" v-if="!cartItems || cartItems.length === 0">
			<image src="/static/images/empty_cart.png" class="empty-image"></image>
			<text class="empty-text">购物车还是空的</text>
			<button class="go-shopping-btn" @click="goShopping">去逛逛</button>
		</view>

		<!-- 购物车商品列表 -->
		<view class="cart-content" v-else>
			<scroll-view class="cart-list" scroll-y="true">
				<view v-for="(item, index) in cartItems" :key="item.id" class="cart-item">
					<!-- 选择框 -->
					<view class="checkbox" @click="toggleSelect(item)">
						<image :src="item.selected ? '/static/images/checked.png' : '/static/images/unchecked.png'"
							class="checkbox-icon"></image>
					</view>

					<!-- 商品图片 -->
					<image :src="item.product.image || '/static/images/default-category.png'" class="item-image"
						mode="aspectFill" @click="goToProductDetail(item.product.id)"></image>

					<!-- 商品信息 -->
					<view class="item-info">
						<text class="item-name" @click="goToProductDetail(item.product.id)">
							{{ item.product.name }}
						</text>
						<text class="item-specs">{{ formatSpecs(item.sku) }}</text>
						<view class="price-qty">
							<text class="item-price">¥{{ formatPrice(item.sku.price) }}</text>

							<!-- 编辑模式下的删除按钮 -->
							<view v-if="isEditMode" class="delete-btn" @click="handleDeleteCartItem(item.id)">
								<text class="delete-text">删除</text>
							</view>

							<!-- 数量控制 -->
							<view v-else class="qty-control">
								<text class="qty-btn minus" :class="{ disabled: item.quantity <= 1 }"
									@click="decreaseQuantity(item)">-</text>
								<text class="qty-num">{{ item.quantity }}</text>
								<text class="qty-btn plus" :class="{ disabled: item.quantity >= item.sku.stock }"
									@click="increaseQuantity(item)">+</text>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 底部结算栏 -->
		<view class="cart-footer" v-if="cartItems && cartItems.length > 0">
			<view class="select-all" @click="toggleSelectAll">
				<image :src="isAllSelected ? '/static/images/checked.png' : '/static/images/unchecked.png'"
					class="checkbox-icon"></image>
				<text class="select-all-text">全选</text>
			</view>

			<!-- 非编辑模式下的结算信息 -->
			<view v-if="!isEditMode" class="checkout-section">
				<view class="total-info">
					<text class="total-label">合计：</text>
					<text class="total-price">¥{{ formatPrice(totalAmount) }}</text>
				</view>
				<button class="checkout-btn" :disabled="selectedCount === 0" @click="checkout">
					结算({{ selectedCount }})
				</button>
			</view>

			<!-- 编辑模式下的批量操作 -->
			<view v-else class="edit-actions">
				<button class="action-btn" @click="batchDelete" :disabled="selectedCount === 0">
					删除所选({{ selectedCount }})
				</button>
				<button class="action-btn move-to-fav" @click="moveToFavorite" :disabled="selectedCount === 0">
					移入收藏
				</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue';
	import {
		onShow
	} from '@dcloudio/uni-app';
	import {
		cartApi
	} from '../../api/cart.js';

	// 状态变量
	const cartItems = ref([]);
	const isEditMode = ref(false);
	const loading = ref(false);

	// 计算属性
	const isAllSelected = computed(() => {
		if (!cartItems.value || cartItems.value.length === 0) return false;
		return cartItems.value.every(item => item.selected);
	});

	const selectedCount = computed(() => {
		if (!cartItems.value) return 0;
		return cartItems.value.filter(item => item.selected).length;
	});

	const totalAmount = computed(() => {
		if (!cartItems.value) return 0;
		return cartItems.value
			.filter(item => item.selected)
			.reduce((sum, item) => sum + (item.sku.price * item.quantity), 0);
	});

	// 格式化价格显示
	const formatPrice = (price) => {
		if (typeof price !== 'number') {
			price = parseFloat(price);
		}
		if (isNaN(price)) {
			return '0.00';
		}
		return price.toFixed(2);
	};

	// 格式化规格显示
	const formatSpecs = (sku) => {
		if (!sku || !sku.specs) return '默认规格';
		try {
			if (typeof sku.specs === 'string') {
				// 检查是否已经是中文规格描述字符串（不是JSON格式）
				if (/^[\u4e00-\u9fa5]/.test(sku.specs) || !sku.specs.startsWith('{')) {
					// 如果是中文字符开头或不是以{开头，直接返回原字符串
					return sku.specs;
				}
				const specs = JSON.parse(sku.specs);
				return Object.values(specs).join(' / ');
			}
			return Object.values(sku.specs).join(' / ');
		} catch (e) {
			console.error('规格解析错误:', e);
			// 如果解析失败，直接返回原始规格字符串
			return sku.specs || '默认规格';
		}
	};

	// 加载购物车数据
	const loadCartData = async () => {
		try {
			loading.value = true;
			const res = await cartApi.getCart();
			if (res.code === 200) {
				cartItems.value = res.data.items || [];
				
				// 更新购物车角标
				const totalCount = cartItems.value.length;
				if (totalCount > 0) {
					uni.setTabBarBadge({
						index: 2, // 购物车的tabBar索引
						text: String(totalCount)
					});
				} else {
					uni.removeTabBarBadge({
						index: 2
					});
				}
			} else {
				uni.showToast({
					title: res.msg || '获取购物车失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('获取购物车数据失败:', error);
			uni.showToast({
				title: '获取购物车失败，请稍后再试',
				icon: 'none'
			});
		} finally {
			loading.value = false;
			uni.hideLoading();
		}
	};

	// 切换编辑模式
	const toggleEditMode = () => {
		isEditMode.value = !isEditMode.value;
	};

	// 切换选中状态
	const toggleSelect = async (item) => {
		try {
			const newSelectedState = !item.selected;
			const res = await cartApi.toggleCartItemSelection(item.id, newSelectedState);
			if (res.code === 200) {
				// 更新本地状态
				item.selected = newSelectedState;
			} else {
				uni.showToast({
					title: res.msg || '操作失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('切换选中状态失败:', error);
			uni.showToast({
				title: '操作失败，请稍后再试',
				icon: 'none'
			});
		}
	};

	// 全选/取消全选
	const toggleSelectAll = async () => {
		const newState = !isAllSelected.value;
		try {
			const res = await cartApi.toggleAllCartItemsSelection(newState);
			if (res.code === 200) {
				// 更新所有商品的选中状态
				cartItems.value.forEach(item => {
					item.selected = newState;
				});
			} else {
				uni.showToast({
					title: res.msg || '操作失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('全选/取消全选失败:', error);
			uni.showToast({
				title: '操作失败，请稍后再试',
				icon: 'none'
			});
		}
	};

	// 增加商品数量
	const increaseQuantity = async (item) => {
		if (item.quantity >= item.sku.stock) return;

		try {
			const newQuantity = item.quantity + 1;
			const res = await cartApi.updateCartItem(item.id, {
				quantity: newQuantity
			});
			if (res.code === 200) {
				item.quantity = newQuantity;
			} else {
				uni.showToast({
					title: res.msg || '更新数量失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('增加数量失败:', error);
			uni.showToast({
				title: '操作失败，请稍后再试',
				icon: 'none'
			});
		}
	};

	// 减少商品数量
	const decreaseQuantity = async (item) => {
		if (item.quantity <= 1) return;

		try {
			const newQuantity = item.quantity - 1;
			const res = await cartApi.updateCartItem(item.id, {
				quantity: newQuantity
			});
			if (res.code === 200) {
				item.quantity = newQuantity;
			} else {
				uni.showToast({
					title: res.msg || '更新数量失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('减少数量失败:', error);
			uni.showToast({
				title: '操作失败，请稍后再试',
				icon: 'none'
			});
		}
	};

	// 删除单个商品
	const handleDeleteCartItem = async (itemId) => {
		uni.showModal({
			title: '提示',
			content: '确定要删除这个商品吗？',
			success: async (res) => {
				if (res.confirm) {
					try {
						const response = await cartApi.deleteCartItem(itemId);
						if (response.code === 200) {
							// 从本地列表中移除该商品
							cartItems.value = cartItems.value.filter(item => item.id !== itemId);
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
							
							// 更新购物车角标
							const totalCount = cartItems.value.length;
							if (totalCount > 0) {
								uni.setTabBarBadge({
									index: 2,
									text: String(totalCount)
								});
							} else {
								uni.removeTabBarBadge({
									index: 2
								});
							}
						} else {
							uni.showToast({
								title: response.msg || '删除失败',
								icon: 'none'
							});
						}
					} catch (error) {
						console.error('删除商品失败:', error);
						uni.showToast({
							title: '删除失败，请稍后再试',
							icon: 'none'
						});
					}
				}
			}
		});
	};

	// 批量删除商品
	const batchDelete = () => {
		const selectedItems = cartItems.value.filter(item => item.selected);
		if (selectedItems.length === 0) return;

		uni.showModal({
			title: '提示',
			content: `确定要删除选中的 ${selectedItems.length} 个商品吗？`,
			success: async (res) => {
				if (res.confirm) {
					try {
						const selectedIds = selectedItems.map(item => item.id);
						const response = await cartApi.batchDeleteCartItems(selectedIds);
						if (response.code === 200) {
							// 从本地列表中移除选中的商品
							cartItems.value = cartItems.value.filter(item => !item.selected);
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
							
							// 更新购物车角标
							const totalCount = cartItems.value.length;
							if (totalCount > 0) {
								uni.setTabBarBadge({
									index: 2,
									text: String(totalCount)
								});
							} else {
								uni.removeTabBarBadge({
									index: 2
								});
							}
						} else {
							uni.showToast({
								title: response.msg || '删除失败',
								icon: 'none'
							});
						}
					} catch (error) {
						console.error('批量删除商品失败:', error);
						uni.showToast({
							title: '删除失败，请稍后再试',
							icon: 'none'
						});
					}
				}
			}
		});
	};

	// 移入收藏
	const moveToFavorite = () => {
		const selectedItems = cartItems.value.filter(item => item.selected);
		if (selectedItems.length === 0) return;

		uni.showToast({
			title: '收藏功能尚未实现',
			icon: 'none'
		});

		// 实际实现时应调用收藏API，然后删除购物车中的对应商品
	};

	// 前往商品详情
	const goToProductDetail = (productId) => {
		uni.navigateTo({
			url: `/pages/product/detail?id=${productId}`
		});
	};

	// 去购物
	const goShopping = () => {
		uni.switchTab({
			url: '/pages/index/index'
		});
	};

	// 去结算
	const checkout = () => {
		const selectedItems = cartItems.value.filter(item => item.selected);
		if (selectedItems.length === 0) {
			uni.showToast({
				title: '请先选择商品',
				icon: 'none'
			});
			return;
		}

		// 获取所选商品ID
		const cartItemIds = selectedItems.map(item => item.id).join(',');

		// 跳转到订单确认页面
		uni.navigateTo({
			url: `/pages/order/confirm?cart_item_ids=${cartItemIds}`
		});
	};

	onShow(() => {
		uni.showLoading({
			title: '加载中...'
		});
		loadCartData();
	})
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 100rpx;
		/* 为底部结算栏留出空间 */
	}

	.cart-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #fff;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.cart-title {
		font-size: 34rpx;
		font-weight: bold;
	}

	.edit-text {
		font-size: 28rpx;
		color: #666;
	}

	.empty-cart {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}

	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 40rpx;
	}

	.go-shopping-btn {
		width: 240rpx;
		height: 70rpx;
		line-height: 70rpx;
		font-size: 28rpx;
		color: #fff;
		background-color: #ff6700;
		border-radius: 35rpx;
	}

	.cart-content {
		flex: 1;
	}

	.cart-list {
		padding: 20rpx;
		width: 95%;
	}

	.cart-item {
		display: flex;
		align-items: center;
		background: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		padding: 20rpx 20rpx 20rpx 20rpx; /* 左右都加内边距 */
		box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
		overflow: hidden; /* 新增，防止子项溢出 */
	}

	.checkbox {
		display: flex;
		align-items: center;
		margin-right: 20rpx;
	}

	.checkbox-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.item-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 8rpx;
	}

	.item-info {
		flex: 1 1 0;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		min-width: 0; /* 保证子项不会撑破 */
		overflow: hidden;
		height: 160rpx;
		margin-left: 20rpx;
	}

	.item-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 8rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		max-width: 100%; /* 新增，防止超出 */
	}

	.item-specs {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 20rpx;
	}

	.price-qty {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		overflow: hidden;
		min-width: 0; /* 新增 */
	}

	.item-price {
		font-size: 32rpx;
		color: #ff6700;
		font-weight: bold;
		flex-shrink: 0; /* 新增 */
	}

	.delete-btn {
		padding: 10rpx 20rpx;
		background-color: #f5f5f5;
		border-radius: 30rpx;
	}

	.delete-text {
		font-size: 24rpx;
		color: #666;
	}

	.qty-control {
		display: flex;
		align-items: center;
		background: #fff0f0;
		border-radius: 25rpx;
		padding: 0 10rpx;
		height: 50rpx;
		flex-shrink: 0;
		min-width: 80rpx;
		max-width: 120rpx; /* 新增 */
		overflow: hidden;
	}

	.qty-btn {
		font-size: 32rpx;
		color: #ff4757;
		padding: 0 10rpx;
		font-weight: bold;
		user-select: none;
		flex-shrink: 0;
	}

	.qty-btn.disabled {
		color: #ccc;
	}

	.qty-num {
		font-size: 28rpx;
		color: #333;
		min-width: 36rpx;
		max-width: 60rpx;
		text-align: center;
		margin: 0 6rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		flex-shrink: 0;
	}

	.cart-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 30rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.select-all {
		display: flex;
		align-items: center;
	}

	.select-all-text {
		font-size: 28rpx;
		margin-left: 10rpx;
	}

	.checkout-section {
		display: flex;
		align-items: center;
	}

	.total-info {
		margin-right: 20rpx;
	}

	.total-label {
		font-size: 26rpx;
		color: #666;
	}

	.total-price {
		font-size: 34rpx;
		color: #ff6700;
		font-weight: bold;
	}

	.checkout-btn {
		width: 200rpx;
		height: 70rpx;
		line-height: 70rpx;
		font-size: 28rpx;
		color: #fff;
		background-color: #ff6700;
		border-radius: 35rpx;
	}

	.checkout-btn[disabled] {
		background-color: #ccc;
	}

	.edit-actions {
		display: flex;
	}

	.action-btn {
		width: 180rpx;
		height: 70rpx;
		line-height: 70rpx;
		font-size: 26rpx;
		color: #fff;
		background-color: #ff6700;
		border-radius: 35rpx;
		margin-left: 20rpx;
	}

	.action-btn.move-to-fav {
		background-color: #666;
	}

	.action-btn[disabled] {
		background-color: #ccc;
	}
</style>